package util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import common.Constant;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.util.List;

public class DimUtil {

    public static JSONObject readDimFromPhoenix(Connection conn, String table, Object id) throws Exception {
        String sql = "select * from  " + table + " where id =?";


        List<JSONObject> queryList = JDBCUtil.getQueryList(conn, sql, new Object[]{id.toString()}, JSONObject.class);
        if (queryList != null && queryList.size() > 0) {
            return queryList.get(0);
        }
        return new JSONObject();
    }

    //读取redis缓存
    public static JSONObject readDimFromRedis(Jedis jedis, String table, Object id, Integer databaseNum) {
        jedis.select(databaseNum);
        String key = table + ":" + id;
        String str = jedis.get(key);
        JSONObject dim = null;
        if (str != null) {
            // 每读一个维度, 应该重新计算一个24小时的过期时间   更新过期时间
            dim = JSON.parseObject(str);
            jedis.expire(key, Constant.REDIS_EXPIRE_TIME);
        }
        return dim;
    }

    //将hbase维度数据写入缓存
    public static void saveDimToRedis(Jedis jedis, String table, Object id, Integer databaseNum, JSONObject dim) {
        jedis.select(databaseNum);
        String key = table + ":" + id;
        String value = dim.toString();
        jedis.setex(key, Constant.REDIS_EXPIRE_TIME, value);
    }

    public static JSONObject readDim(Connection conn, Jedis jedis, String table, Object id, Integer databaseNum) throws Exception {
        //先读取redis缓存,没有数据再读取hbase,然后将hbase数据写入缓存
        JSONObject dim = readDimFromRedis(jedis, table, id, databaseNum);
        if (dim == null) {
            dim = readDimFromPhoenix(conn, table, id);
            System.out.println("从phoenix获取数据................." + table + " " + id);
            saveDimToRedis(jedis, table, id, databaseNum, dim);
        } else {
            System.out.println("从redis获取数据...................." + table + " " + id);
        }
        return dim;
    }

}
